<?php


class shoppingcart{

	/**
	*会员ID 
	*@var int 
	*/
	public $fid;

	/**
	*商品ID 
	*@var int  
	*/
	public $pid;

	/**
	 *票付通内部接口对象
	 *@var object
	 */
	public $s;

	/**
	 *购物车信息
	 *@var array
	 */
	public $scinfo=array();

	/**
	 *库存-销量
	 *@var array
	 */
	public $s_info=array();

	/**
	 *用于前端显示的JSON格式购物车信息
	 *@var array
	 */
	public $n_info=array();
	/**
	 *构造函数.
	 *@var array 包含里购物车里的景区和票及库存剩余的信息
	 *@int $memberID 会员ID
	 *@param $s 票付通内部接口对象
	 */
	public function __construct($s,$memberID){
		$this->fid = $memberID;		 
		$this->s=$s;            
	}

	/**
	 *购物车信息函数.
	 *@return array 返回购物车信息数组
	 */
	public function info(){
    //原语句如下  现在要把 leftjoin全部拆开依次查询
        $str = "SELECT l.title as ltitle,l.p_type,s.id,p.id as pid,s.lid,s.tid,s.num,s.starttime,s.endtime,s.isSelected,t.title,t.tprice from uu_shoppingcart s left join uu_land l on s.lid=l.id left join uu_jq_ticket t on s.tid=t.id left join uu_products p on t.pid=p.id where s.fid=$this->fid";
        // echo $str;
        $str = "select id,lid,tid,num,starttime,endtime,1 as isSelected,aid from uu_shoppingcart where fid=$this->fid and access='{$_SERVER['HTTP_HOST']}'";
        $GLOBALS['le']->query($str);
        while($arr=$GLOBALS['le']->fetch_assoc()){
            $this->scinfo[]=$arr;
        }
        // print_r($this->scinfo);
        $today = date("Y-m-d");
        if(empty($this->scinfo))return  $this->scinfo;
        foreach($this->scinfo as $key => $val){ 
            $str = "select pid,title,ddays from uu_jq_ticket where id={$val['tid']} limit 1";
            $GLOBALS['le']->query($str);
            $tinfo = $GLOBALS['le']->fetch_assoc();
            // print_r($tinfo);
            // echo "<br/>";
                  
            //$ps = $this->s->get_Dynamic_Price_Merge($tinfo['pid'],$today,0,"","",1,1); 
            $ps = $this->s->Dynamic_Price_And_Storage('',$tinfo['pid'],$today,3,1,0,'');
            $ps = simplexml_load_string($ps);
            // print_r($ps);exit;  
            $this->scinfo[$key]['storage']=(string)$ps->Rec->UUstorage;
            if($v['storage']===null){   
                $this->scinfo[$key]['storage']=10000;               
            }
            //取出有价钱的最近日期
            /*
            当今天不在某个有效的时间段内时 把临时时间逐步往离现在的时间段近的方向推进
            当今天在某个有效的时间段内时 直接取
            */
            $tic_startdate = "2030-12-30";
            // $this->scinfo[$key]['starttime'] = null;
            foreach($ps->Rec as $ticdata){ 
                if($tic_startdate>(string)$ticdata->UUstart_date && $this->scinfo[$key]['starttime']<=(string)$ticdata->UUstart_date)
                $tic_startdate = (string)$ticdata->UUstart_date;
            
                if($this->scinfo[$key]['starttime']>=(string)$ticdata->UUstart_date && $this->scinfo[$key]['starttime']<(string)$ticdata->UUend_date){
                    $easy_date = $this->scinfo[$key]['starttime'];
                    break;
                }                
                
            }
            $this->scinfo[$key]['starttime'] = $easy_date ? $this->scinfo[$key]['starttime']:$tic_startdate;
            if ((strtotime($this->scinfo[$key]['starttime']) - strtotime($today))/86400<$tinfo['ddays'])
                $this->scinfo[$key]['starttime'] = date('Y-m-d',strtotime("+".$tinfo['ddays'].'days'));
            $startdate = $this->scinfo[$key]['starttime'];
            $this->scinfo[$key]['starttime'] =date("Y-m-d",strtotime("$startdate"));
            $this->scinfo[$key]['endtime'] =date("Y-m-d",strtotime("$startdate+1day"));
            
            $price = simplexml_load_string($this->s->Dynamic_Price_And_Storage('',$tinfo['pid'],"$startdate",1,1));           
            $tinfo['tprice'] = ((string)$price->Rec->UUsprice)/100;
            
            $str = "select title as ltitle,p_type from uu_land where id={$val['lid']} limit 1";
            $GLOBALS['le']->query($str);
            $linfo = $GLOBALS['le']->fetch_assoc();            
            
            $this->scinfo[$key] = array_merge($this->scinfo[$key],$tinfo,$linfo); 
            
        }
      return $this->scinfo;
    }

	/**
	 *用于前端显示的购物车信息 还需要转换一次JSON
	 *@return array
	 */
	public function n_info(){
        $this->scinfo=$this->info();        
        $this->n_info['code']=200;
        $this->n_info['list']=array();   
        // print_r($this->scinfo);
        // exit;
        foreach($this->scinfo as $k => $v){
         $total+=$v['num']*$v['tprice'];
            if(!array_key_exists($v['lid'], $this->n_info['list'])){            
                if(!($v['p_type']==C)){//C是酒店类型 多一个结束时间的字段
                    $this->n_info['list'][$v['lid']]=array(
                       'aid'=>$v['aid'],'type'=>$v['p_type'],'title'=>$v['ltitle'],'isSelected'=>$v['isSelected']);
                      $this->n_info['list'][$v['lid']]['subs'][$v['id']]=array(
                              'tid'=>$v['tid'],'pid'=>$v['pid'],'title'=>$v['title'],'price'=>$v['tprice'],'count'=>$v['num'],'date'=>$v['starttime'],'storage'=>$v['storage']);
                    }else{
                        $this->n_info['list'][$v['lid']]=array(
                            'aid'=>$v['aid'],'type'=>$v['p_type'],'title'=>$v['ltitle'],'isSelected'=>$v['isSelected']);
                          $this->n_info['list'][$v['lid']]['subs'][$v['id']]=array(
                                 'tid'=>$v['tid'],'pid'=>$v['pid'],'title'=>$v['title'],'price'=>$v['tprice'],'count'=>$v['num'],'date'=>array('begin'=>$v['starttime'],'end'=>$v['endtime']),'storage'=>$v['storage']);
                }
            }else{
                if(!($v['p_type']==C)){
                  $this->n_info['list'][$v['lid']]['subs'][$v['id']]=array(
                    'tid'=>$v['tid'],'pid'=>$v['pid'],'title'=>$v['title'],'price'=>$v['tprice'],'count'=>$v['num'],'date'=>$v['starttime'],'storage'=>$v['storage']
                    );
               }else{
                 $this->n_info['list'][$v['lid']]['subs'][$v['id']]=array(
                     'tid'=>$v['tid'],'pid'=>$v['pid'],'title'=>$v['title'],'price'=>$v['tprice'],'count'=>$v['num'],'date'=>array('begin'=>$v['starttime'],'end'=>$v['endtime']),'storage'=>$v['storage']);                 
                }
            }
            $this->n_info['total']=$total;
        }
        // print_r($this->n_info);
        // exit;
        return $this->n_info;
    }
	/**
	 *购物车信息函数.
	 *@return JSON 返回购物车JSON信息数组 当为空时把中括号换成大括号
	 */
	public function j_info(){
		// return str_replace("]","}",str_replace("[","{",json_encode($this->n_info())));
        $this->n_info();
        if(empty($this->n_info['list'])){
           $this->n_info=str_replace("]","}",str_replace("[","{",json_encode($this->n_info)));
            return $this->n_info;
       }else{          
            return json_encode($this->n_info);
        }
        
	}
    //前端实时更改购物车信息
	public function change($type,$tid,$value){
		$str = "UPDATE uu_shoppingcart set $type='$value' where fid=$this->fid and tid=$tid limit 1";
		$GLOBALS['le']->query($str);
        // $sel = "select * from uu_shoppingcart where fid=".$this->fid ."and tid='$tid'";
        // $GLOBALS['le']->query($sel);
        // $r=array();
        // while($row = $GLOBALS['le']->fetch_assoc()){
        // $r[]=$row;}
        // print_r($r); 		
	}
    
    //清空当前用户的购物车
    public function deleteall(){
        $str="DELETE from uu_shoppingcart where fid=$this->fid";
        $GLOBALS['le']->query($str);     
    }
    
    //有选择的删除
    public function delete($id){        
        $id = $id+0;
        $str = "DELETE from uu_shoppingcart where id=$id limit 1";
		$GLOBALS['le']->query($str); 
    }

    //将商品增加到购物车
    //按不同票类人数来添加  	
    public function addwhole($lid,$starttime,$adult,$stu,$eld,$aid=0){ 
        $lid = $lid+0;
        $aid = $aid+0;
		$str = "SELECT id from uu_products where contact_id=$lid limit 1";
		$GLOBALS['le']->query($str);
        $r = array();
        while($row = $GLOBALS['le']->fetch_assoc()){
        	$r[]=$row;
    	}
    	foreach($r as $v){
    		$pid = $v['id'];
            $str = "SELECT title,id from uu_jq_ticket where pid=$pid limit 1";
            $GLOBALS['le']->query($str);
            $row = $GLOBALS['le']->fetch_assoc();
            $eld = $eld+0;
            $stu = $stu+0;
            $adult = $adult+0;  
             // var_dump($eld);
             // var_dump($stu);
             // var_dump($adult);
            switch($row['title']){
                case "老人票":
                    $num = $eld;
                    break;
                case "学生票":
                    $num = $stu;
                    break;
                case "成人票":
                    $num = $adult;
                    break;
                default:
                    $num = $adult+$stu+$eld;
            }
            $tid = $row['id'];
            $starttime=($starttime=="")?date("Y-m-d"):$starttime;
            $str = "SELECT tid,fid from uu_shoppingcart where tid={$row['id']} and fid=$this->fid limit 1";
            $GLOBALS['le']->query($str);
            $row = $GLOBALS['le']->fetch_assoc();
            if(isset($row['tid']) && isset($row['fid'])){
                $str = "UPDATE uu_shoppingcart set starttime='$starttime',num=num+$num where tid={$row['tid']} and fid=$this->fid limit 1";
                $GLOBALS['le']->query($str);
            }else{
                $str = "INSERT into uu_shoppingcart (fid,lid,starttime,tid,num,aid,access) values ($this->fid,$lid,'$starttime',$tid,$num,$aid,'{$_SERVER['HTTP_HOST']}')";
                $GLOBALS['le']->query($str);
            }
   		 }	    
	}

	// 添加酒店到购物车	
	public function addhotel($arr,$aid=0){
        $aid = $aid+0;
		foreach($arr as $k=>$v){
			$pid = $k+0;
			$str="SELECT landid,id from uu_jq_ticket where pid=$pid limit 1";
			$GLOBALS['le']->query($str);
			$row = $GLOBALS['le']->fetch_assoc();
			$lid = $row['landid'];
            $tid= $row['id'];
			$starttime = $v['begin'];
            $endtime = $v['end'];
            $endtime=($endtime=="")?date('Y-m-d',strtotime('+1day')):$endtime;
            $starttime=($starttime=="")?date('Y-m-d'):$starttime;   			
			$num = $v['count']+0;
            $str = "SELECT tid,fid from uu_shoppingcart where tid=$tid and fid=$this->fid limit 1";
            $GLOBALS['le']->query($str);
            $row = $GLOBALS['le']->fetch_assoc();
            if(isset($row['tid']) && isset($row['fid'])){
                $str="UPDATE uu_shoppingcart set starttime='$starttime',endtime='$endtime',num=num+$num where tid=$tid and fid=$this->fid limit 1";
                $GLOBALS['le']->query($str);
            }else{
                $str="INSERT into uu_shoppingcart (fid,lid,starttime,endtime,tid,num,aid,access) values ($this->fid,$lid,'$starttime','$endtime',$tid,$num,$aid,'{$_SERVER['HTTP_HOST']}')";
                $GLOBALS['le']->query($str);
            }
        }
	}

	//添加餐饮
	public function addG($lid,$v,$starttime,$aid=0){
        $lid=$lid+0;        
        $aid = $aid+0;
        foreach($v as $key => $val){
            $pid=$key+0;            
            $sql = "select id from uu_jq_ticket where pid=$pid";
            $GLOBALS['le']->query($sql);
            $GLOBALS['le']->fetch_assoc();
            $tid = $GLOBALS['le']->f('id');
            $snn=$val+0;
            $starttime=($starttime=="")?date('Y-m-d'):$starttime;
            for($i=0;$i<$snn;$i++){
                if($i==100)break;                
                $str = "INSERT into uu_shoppingcart (fid,lid,starttime,tid,num,aid,access) values ($this->fid,$lid,'$starttime',$tid,1,$aid,'{$_SERVER['HTTP_HOST']}')";
                $GLOBALS['le']->query($str);             
            }            
        }
    }
    
    //单个产品添加
    public function addone($p_type,$lid,$tid,$num,$aid=0){
        $lid = $lid+0;
        $tid = $tid+0;
        if($lid==0 ||$tid ==0) {
            print_r(json_encode(array('code'=>104)));
            exit;
        }        
        $starttime = date("Y-m-d",strtotime("+1day"));
        $num = $num+0;
         if($p_type==G){
            $str = "INSERT INTO uu_shoppingcart  (fid,lid,starttime,endtime,tid,num,aid,access) values ($this->fid,$lid,'$starttime','$endtime',$tid,$num,$aid,'{$_SERVER['HTTP_HOST']}')";
        }else{
            $str = "SELECT tid,fid from uu_shoppingcart where tid=$tid and fid=$this->fid limit 1";
            $GLOBALS['le']->query($str);
            $row = $GLOBALS['le']->fetch_assoc();
            if(isset($row['tid']) && isset($row['fid'])){
                $str = "UPDATE uu_shoppingcart set num=num+$num where tid=$tid and fid=$this->fid limit 1";
            }else{
                if($p_type==C){
                    $endtime = date("Y-m-d",strtotime("+2day"));
                }else{
                    $endtime ="";
                }
                $str = "INSERT INTO uu_shoppingcart  (fid,lid,starttime,endtime,tid,num,aid,access) values ($this->fid,$lid,'$starttime','$endtime',$tid,$num,$aid,'{$_SERVER['HTTP_HOST']}')";
            }
        }
        $GLOBALS['le']->query($str);  
    }
}  
?>